package blog.service.impl;

import blog.mapper.UserMapper;
import blog.pojo.ResultVo;
import blog.pojo.User;
import blog.service.UserService;
import blog.utils.JwtUtils;
import blog.utils.RsaUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.security.PrivateKey;

/**
 * @author HuLin
 * @version 1.0
 * @date 2022/9/16 20:57
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResultVo login(User loginUser) {
//        login
	  QueryWrapper queryWrapper = new QueryWrapper();
	  queryWrapper.eq("username",loginUser.getUsername());
	  User user = userMapper.selectOne(queryWrapper);
	  if(user == null){
	      return new ResultVo(100,"user no exist");
	  }
	  //mysql不分Aa
	  if(!loginUser.getUsername().equals(user.getUsername())){
	      return new ResultVo(100,"user mistake");
	  }
	  //比较密码
	  if (!DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes()).equals(user.getPassword())){
		return new ResultVo(100,"password mistake");
	  }
//	  username+password √-> token
	  try {
		PrivateKey privateKey = RsaUtils.getPrivateKey(new ClassPathResource("key/rsa.pri").getInputStream());
		user.setPassword("");
		String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 15);
		return new ResultVo(0,token,user);
	  } catch (Exception e) {
		e.printStackTrace();
	  }
	  return new ResultVo(0,"token fail",user);
    }
}
